from Tkinter import *
import tkMessageBox
import BookProcessor
import UserProcessor

class MainFrame(Frame):
	bookProcessor = BookProcessor.BookProcessor()
	userProcessor = UserProcessor.UserProcessor()
	
	def __init__(self, master):
		Frame.__init__(self, master)	
		self.grid()
		
		self.font=('Helvetica', 22, 'normal')
		self.label_init = Label(self, text="Welcome to BookMarker Library", font=self.font).grid()
			
		"""Blank line"""
		self.blank = Label(self, text="").grid()
		
		"""Search For Book Block"""
		self.label1_init = Label(self, text="Search for a book").grid()
		self.label1a_init = Label(self, text="Enter a title/author/ISBN/keyword:")
				      
		self.label1a_init.grid()
   		self.text1_init = Entry(self, name = "text1")
   		self.text1_init.insert(INSERT, "")
		self.text1_init.grid()
		self.input1_init = Button(self, text="Search", command=self.BookSearch).grid()
          			
		"""Blank line"""
		self.blank = Label(self, text="").grid()
		
		"""Check out Book Block"""
		self.label2_init = Label(self, text="Check out book/books").grid()
		self.label2a_init = Label(self, text="Enter User Name:").grid()
		self.text2_init = Entry( self, name = "text2" )
		self.text2_init.insert( INSERT, "" )
		self.text2_init.grid()
		self.input2_init = Button(self, text="Checkout", command=self.CheckOut).grid()
		
		#Blank line
		self.blank = Label(self, text="").grid()

		
		"""Return Book Block"""
		self.label8_init = Label(self, text="Return Book").grid()
		self.label8a_init = Label(self, text="Enter Book Id:").grid()
		self.text8_init = Entry( self, name = "text8" )
		self.text8_init.insert( INSERT, "" )
		self.text8_init.grid()
		self.input8_init = Button(self, text="Return", command=self.Return).grid()
		
		#Blank line
		self.blank = Label(self, text="").grid()		
		
		
		
		
		#Find Books checked out
		self.label3_init = Label(self, text="Find books checked out").grid()
		self.label3a_init = Label(self, text="Enter User Name:").grid()
		self.text3_init = Entry( self, name = "text3" )
		self.text3_init.insert( INSERT, "" )
		self.text3_init.grid()
		self.input3_init = Button(self, text="FindCheckout", command=self.FindCheckout).grid()
		
		#Blank line
		self.blank = Label(self, text="").grid()

		"""List Books in Library"""
		self.label4_init = Label(self, text="List Books in Library").grid()
		self.input4_init = Button(self, text="Show All", command=self.listBook)
		self.input4_init.grid()
		
	def MainPage(self):
		"""Get Back to Main search display"""
		self.destroy()
		self.__init__(self.master)	
		
	def BookSearch(self):
		#Get the search term first
		name=self.text1_init.get()
		foundBooks=self.bookProcessor.searchBook(keyword=name)
		
		#Remove myself
		self.destroy()
		
		#Create a new frame for result display
		Frame.__init__(self,self.master)
		self.grid()
		
		self.label = Label(self, text="Searching For : "+name).grid()
		#Blank line
		self.blank = Label(self, text="").grid()
		
		#self.label = Label(self, text=foundBooks).grid(column=0)
		
		#Creating a books list box for foundBooks
		self.listbox = Listbox(self,width=70, height=25)
		if foundBooks:
			self.label = Label(self, text="Results found:").grid(column=0)
			self.listbox.grid()
			for keys in foundBooks.keys():
				self.listbox.insert(0, '')
				if foundBooks[keys].isAvailable():
					self.listbox.insert(0, "Availability: Yes")
				else:
					self.listbox.insert(0, "Availability: No")
				self.listbox.insert(0, "Category: "+foundBooks[keys].getCategory())
				self.listbox.insert(0, "ISBN: "+foundBooks[keys].getIsbn())
				self.listbox.insert(0, "Author: "+foundBooks[keys].getAuthor())
				self.listbox.insert(0, "Book ID: "+foundBooks[keys].getBookId())
				self.listbox.insert(0, "Book Title: "+foundBooks[keys].getTitle())
				
		else:
			self.label = Label(self, text="No Results found").grid(column=0)		
		
		#Blank line
		self.labelBlank3 = Label(self, text="").grid()
		self.input1 = Button(self, text="Back To Main Page", command=self.MainPage).grid()
							
	def CheckOut(self):
		username=self.text2_init.get()
		# if user does not exist
		userid = self.userProcessor.userExists(username) 
		if userid != '-1':
			self._currentUser = self.userProcessor.getUser(userid)			
			
			self.destroy()
			# create a new frame for checkout
			Frame.__init__(self,self.master)
			self.grid()
			self.label1 = Label(self, text="Welcome " + username).grid()
			
			"""Check out Book Block"""
			self.label2 = Label(self, text="Please Enter the book ID").grid()
			
			self.text2 = Entry( self, name = "text5" )
			self.text2.insert( INSERT, "" )
			self.text2.grid()
			self.button1 = Button(self, text="Checkout", command=self.checkoutBook).grid()
			
			#Blank line
			self.blank = Label(self, text="").grid()
			self.button2 = Button(self, text="Back To Main Page", command=self.MainPage).grid()
		
		else:
			
			self.destroy()
			# create a new frame for checkout
			Frame.__init__(self,self.master)
			self.grid()
			self.label3 = Label(self, text="Unable to locate username : " + username).grid()
			self.label3 = Label(self, text="Please Create New User or Go Back To Main Page").grid()
			#Blank line
			self.blank = Label(self, text="").grid()
	
			self.label4 = Label(self, text="Create New User").grid()
			self.label4 = Label(self, text="User Name:").grid()
			self.text3 = Entry( self, name = "text16" )
			self.text3.insert( INSERT, username )
			self.text3.grid()
			
			self.label5 = Label(self, text="User Email Address:").grid()
			self.text4 = Entry( self, name = "text17" )
			self.text4.insert( INSERT, "" )
			self.text4.grid()
			self.button3 = Button(self, text="Submit", command=self.createNewUser).grid()	
						
			#Blank line
			self.blank = Label(self, text="").grid()
					
			#Blank line
			self.blank = Label(self, text="").grid()
			self.button4 = Button(self, text="Back To Main Page", command=self.MainPage).grid()

	def Return(self):
		bookid=self.text8_init.get()
		if self.bookProcessor.returnBook(bookid):
			self.userProcessor.delBookfromUser(bookid)
			self.destroy()
			# create a new frame for return
			Frame.__init__(self,self.master)
			self.grid()
			self.label5b = Label(self, text = 'Book [' + bookid + '] "' + self.bookDictionary[bookid].getTitle() + '" has returned. ').grid()

			#Blank line
			self.blank = Label(self, text="").grid()
			
			#Blank line
			self.blank = Label(self, text="").grid()
			self.button4 = Button(self, text="Back To Main Page", command=self.MainPage).grid()
		else:
			self.destroy()
			# create a new frame for return
			Frame.__init__(self,self.master)
			self.grid()
			self.label5b = Label(self, text = 'Book [' + bookid + '] "' + self.bookDictionary[bookid].getTitle() + '" has already returned. ').grid()

			#Blank line
			self.blank = Label(self, text="").grid()
			
			#Blank line
			self.blank = Label(self, text="").grid()
			self.button4 = Button(self, text="Back To Main Page", command=self.MainPage).grid()
		
	def checkoutBook(self):
		bookid = self.text2.get()
		userid = self._currentUser.getUserId()
		self.bookDictionary = self.bookProcessor.getBookDictionary()
		
		if not self.bookProcessor.checkoutBook(bookid):
			self.label5b = Label(self, text = 'Unable to checkout the book, the book has checked out.').grid()
		elif not self.userProcessor.addBookToUser(userid, bookid):
			self.label5b = Label(self, text = 'Unable to add the book to user. Max number (2) reached.').grid()
			# roll back
			if not self.bookProcessor.returnBook(bookid):
				self.label5b = Label(self, text = 'Unable to roll back.').grid()
		else:
			self.label5b = Label(self, text = 'Book [' + bookid + '] "' + self.bookDictionary[bookid].getTitle() + '" has checked out. Return at [' + str(self.bookDictionary[bookid].getReturnDate()) + ']').grid()
			
	
	def FindCheckout(self):
		username=self.text3_init.get()
		# if user does not exist
		userid = self.userProcessor.userExists(username) 
		if userid != '-1':
			self._currentUser = self.userProcessor.getUser(userid)			
		
			"""Remove myself"""
			self.destroy()
			"""Create a new frame for result display"""
			Frame.__init__(self,self.master)
			self.grid()
			self.label = Label(self, text="Current List of Books Checked Out: ").grid()
			self.bookDictionary = self.bookProcessor.getBookDictionary()
			bookList = self._currentUser.getBookList()
			if bookList:
				self.listbox = Listbox(self, width=70, height=25)
				self.listbox.grid()
				for bookId in bookList:		
					book = self.bookDictionary[bookId]
					self.listbox.insert(0, " ")
					self.listbox.insert(0, "Return Date: " + str(book.getReturnDate()))				
					self.listbox.insert(0, "ISBN: " + book.getIsbn())				
					self.listbox.insert(0, "Category: " + book.getCategory())
					self.listbox.insert(0, "Author: " + book.getAuthor())	
					self.listbox.insert(0, "Book Title: " + book.getTitle())
					self.listbox.insert(0, "Book ID: " + book.getBookId())				
			else:
				self.label = Label(self, text="No Results found").grid(column=0)
		
			#Blank line
			self.labelBlank3 = Label(self, text="").grid()
			self.input1 = Button(self, text="Back To Main Page", command=self.MainPage).grid()
		else:
			# Todo
			pass
		
		
	def listBook(self):
		"""Remove myself"""
		self.destroy()
		"""Create a new frame for result display"""
		Frame.__init__(self,self.master)
		self.grid()
		self.label = Label(self, text="Current List of Books by title: ").grid()
		self.bookDictionary = self.bookProcessor.getBookDictionary()
		if self.bookDictionary:
			self.listbox = Listbox(self, width=120, height=40)
			self.listbox.grid()
			for keys in self.bookDictionary.keys():
				if (self.bookDictionary[keys].isAvailable()):
					status = 'Available'
				else:
					status = 'CheckedOut'				
				self.listbox.insert(0, '[' + self.bookDictionary[keys].getBookId() + ']  ' + self.bookDictionary[keys].getTitle() + '   [' + status + ']')
		else:
			self.label = Label(self, text="No Results found").grid(column=0)
	
		#Blank line
		self.labelBlank3 = Label(self, text="").grid()
		self.button4 = Button(self, text="Back To Main Page", command=self.MainPage).grid()
		
	def checkEmail(self,email):
		if email.count('@')==1:
			if email.split('@')[1].count('.')==1:
				if len(email.split('@')[0])<65:
					if len(email.split('@')[1])<256:
						   return True
		return False
	
	def createNewUser(self):
		username=self.text3.get()
		useremail=self.text4.get()
		
		if self.checkEmail(useremail)==False:
			tkMessageBox.showerror("Error", "Email Address Incorrect!\nPlease Re-Enter")
		else:
			if self.userProcessor.addUser(username,useremail)==True:
				"""Remove myself"""
				self.destroy()
				"""Create a new frame for result display"""
				Frame.__init__(self,self.master)
				self.grid()
				self.label = Label(self, text="New User " + username + " " + useremail + " Created").grid()
				
				#Blank line
				self.labelBlank3 = Label(self, text="").grid()
				self.input1 = Button(self, text="Back To Main Page", command=self.MainPage).grid()
				
			else:
				"""Remove myself"""
				self.destroy()
				"""Create a new frame for result display"""
				Frame.__init__(self,self.master)
				self.grid()
				self.label = Label(self, text="Unable to complete user creation").grid()
				
				#Blank line
				self.labelBlank3 = Label(self, text="").grid()
				self.input1 = Button(self, text="Back To Main Page", command=self.MainPage).grid()
		
	

				
		

root = Tk()
app = MainFrame(root)
root.title("BookMarker Library")
root.geometry("750x700")
root.mainloop()
